#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
fund_info_detail表统计信息监控脚本
每10秒刷新一次统计信息
"""

import os
import sys
import django  # type: ignore
import time
from datetime import datetime

# 设置Django环境
current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, current_dir)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wealth_backend.settings_mysql')
django.setup()

from data_service.models import FundInfoDetail
from django.db.models import Count, Q  # type: ignore

def clear_screen():
    """清屏"""
    os.system('clear' if os.name == 'posix' else 'cls')

def get_fund_detail_stats():
    """获取fund_info_detail表统计信息"""
    try:
        # 总记录数
        total_count = FundInfoDetail.objects.count()
        
        # 按基金类型统计
        type_stats = FundInfoDetail.objects.values('fund_type').annotate(
            count=Count('fund_type')
        ).order_by('-count')
        
        # 按基金公司统计（前10名）
        company_stats = FundInfoDetail.objects.values('fund_company').annotate(
            count=Count('fund_company')
        ).order_by('-count')[:10]
        
        # 有完整信息的基金数量
        complete_info_count = FundInfoDetail.objects.filter(
            Q(fund_name__isnull=False) & ~Q(fund_name='') &
            Q(fund_type__isnull=False) & ~Q(fund_type='') &
            Q(fund_company__isnull=False) & ~Q(fund_company='')
        ).count()
        
        # 最近更新的记录
        latest_records = FundInfoDetail.objects.order_by('-updated_at')[:5]
        
        # 最新1条数据的全部字段
        latest_1_record = FundInfoDetail.objects.order_by('-updated_at')[:1]
        
        return {
            'total_count': total_count,
            'type_stats': type_stats,
            'company_stats': company_stats,
            'complete_info_count': complete_info_count,
            'latest_records': latest_records,
            'latest_1_record': latest_1_record
        }
    except Exception as e:
        return {'error': str(e)}

def display_stats(stats):
    """显示统计信息"""
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    print("="*80)
    print(f"fund_info_detail表统计信息 - {current_time}")
    print("="*80)
    
    if 'error' in stats:
        print(f"错误: {stats['error']}")
        return
    
    print(f"\n📊 总记录数: {stats['total_count']}")
    print(f"📋 完整信息记录数: {stats['complete_info_count']}")
    print(f"📈 完整度: {stats['complete_info_count']/stats['total_count']*100:.1f}%" if stats['total_count'] > 0 else "📈 完整度: 0%")
    
    print("\n🏷️  基金类型分布:")
    print("-" * 40)
    for item in stats['type_stats']:
        fund_type = item['fund_type'] or '未分类'
        count = item['count']
        percentage = count / stats['total_count'] * 100 if stats['total_count'] > 0 else 0
        print(f"  {fund_type:<20} {count:>6} ({percentage:>5.1f}%)")
    
    print("\n🏢 基金公司分布 (前10名):")
    print("-" * 40)
    for item in stats['company_stats']:
        company = item['fund_company'] or '未知公司'
        count = item['count']
        percentage = count / stats['total_count'] * 100 if stats['total_count'] > 0 else 0
        print(f"  {company:<25} {count:>6} ({percentage:>5.1f}%)")
    
    print("\n🕒 最近更新的5条记录:")
    print("-" * 40)
    for record in stats['latest_records']:
        update_time = record.updated_at.strftime('%m-%d %H:%M:%S')
        print(f"  {record.fund_code} {record.fund_name:<20} {update_time}")
    
    print("\n📋 最新1条数据详细信息:")
    print("-" * 80)
    for i, record in enumerate(stats['latest_1_record'], 1):
        print(f"\n第{i}条记录:")
        print(f"  基金代码: {record.fund_code}")
        print(f"  基金名称: {record.fund_name or '未知'}")
        print(f"  基金全称: {record.fund_full_name or '未知'}")
        print(f"  基金类型: {record.fund_type or '未知'}")
        print(f"  基金公司: {record.fund_company or '未知'}")
        print(f"  成立日期: {record.establishment_date or '未知'}")
        print(f"  最新规模: {record.latest_scale or '未知'}")
        print(f"  基金经理: {record.fund_manager or '未知'}")
        print(f"  托管银行: {record.custodian_bank or '未知'}")
        print(f"  评级机构: {record.rating_agency or '未知'}")
        print(f"  基金评级: {record.fund_rating or '未知'}")
        print(f"  投资策略: {record.investment_strategy or '未知'}")
        print(f"  投资目标: {record.investment_objective or '未知'}")
        print(f"  业绩比较基准: {record.performance_benchmark or '未知'}")
        print(f"  数据来源: {record.data_source or '未知'}")
        print(f"  创建时间: {record.created_at.strftime('%Y-%m-%d %H:%M:%S') if record.created_at else '未知'}")
        print(f"  更新时间: {record.updated_at.strftime('%Y-%m-%d %H:%M:%S') if record.updated_at else '未知'}")
    
    print("\n" + "="*80)
    print("按 Ctrl+C 退出监控")
    print("下次刷新: 10秒后")

def main():
    """主函数"""
    print("启动fund_info_detail表统计信息监控...")
    print("每10秒自动刷新一次")
    print("按 Ctrl+C 退出\n")
    
    try:
        while True:
            clear_screen()
            stats = get_fund_detail_stats()
            display_stats(stats)
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n\n监控已停止")
    except Exception as e:
        print(f"\n\n发生错误: {e}")

if __name__ == '__main__':
    main()